<template>
  <div>
    <el-switch
      style="display: online"
      v-model="draggable"
      active-color="#13ce66"
      inactive-color="#ff4949"
      active-text="允许拖动"
      inactive-text="禁止拖动"
    >
    </el-switch>
    <el-button type="danger" @click="deleteBatch()">批量删除</el-button>
    <br>
    <hr>
    <el-tree
      :data="menu"
      :props="defaultProps"
      show-checkbox
      empty-text="内容为空"
      :expand-on-click-node="false"
      node-key="catId"
      :default-expanded-keys="expanded"
      :draggable="draggable"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="node.level <= 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="data.children.length === 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>

          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="category">
        <el-form-item label="节点名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="节点图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="() => submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      draggable: false,
      menu: [],
      expanded: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      category: {
        name: "",
        parentCid: "",
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: "",
        productUnit: "",
      },
      dialogFormVisible: false,
      title: "",
      dialogTag: "",
      maxLevel: 0,
      updateNodes: [],
    };
  },
  methods: {
    deleteBatch() {
      let selectedNodes = this.$refs.menuTree.getCheckedNodes();
      let nodeNames = [];
      let expanded = selectedNodes[0].parentCid;
      let catIds = [];
      //展开的节点
      selectedNodes.forEach((element) => {
        nodeNames.push(element.name);
        catIds.push(element.catId);
      });
      this.$confirm(`是否删除【${nodeNames}】节点?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(catIds, false),
          })
            .then(({ data }) => {
              this.getMenu();
              this.expanded.push(expanded);
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    handleNodeClick(data) {
      console.log(data);
    },
    getMenu() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      })
        .then(({ data }) => {
          this.menu = data.data;
        })
        .catch((err) => {
          alert(err);
        });
    },
    append(data) {
      this.title = "添加节点";
      this.dialogFormVisible = true;
      this.dialogTag = "append";

      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel * 1 + 1;
      this.category.productUnit = "";
      this.category.icon = "";
      this.category.sort = 0;
      this.category.showStatus = 1;
      this.category.name = "";

      //console.log("append", data);

      const parentCids = [data.catId];
      this.expanded = parentCids;
    },

    remove(node, data) {
      const parentCids = [data.parentCid];
      const ids = [data.catId];
      this.$confirm(`是否删除【${data.name}】节点?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          })
            .then(() => {
              this.$message({
                message: "删除成功！",
                type: "success",
              });
              //更新目录
              this.getMenu();
              //默认展开到删除节点的父节点
              this.expanded = parentCids;
            })
            .catch(() => {
              this.$message.error("删除失败！");
            });
        })
        .catch(() => {});

      //console.log("remove", node, data);
    },
    //保存节点
    saveCategory() {
      //tag
      console.log("============save===========", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      })
        .then(({ data }) => {
          //关闭弹窗
          this.dialogFormVisible = false;
          //添加成功后更新目录
          this.getMenu();
        })
        .catch(() => {});
    },
    //打开编辑节点窗口
    edit(data) {
      console.log(data);
      this.title = "修改节点";
      this.dialogFormVisible = true;
      this.dialogTag = "edit";
      //回显数据
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "post",
        data: this.$http.adornData(data, false),
      })
        .then(({ data }) => {
          console.log("edit---show---data:", data);
          this.category.catId = data.data.catId;
          this.category.name = data.data.name;
          this.category.icon = data.data.icon;
          this.category.productUnit = data.data.productUnit;
        })
        .catch(() => {});

      const parentCids = [data.parentCid];
      this.expanded = parentCids;
    },
    updataCategory() {
      const { catId, name, icon, productUnit } = this.category;
      //todo
      console.log("{catId,name,icon,productUnit}=", {
        catId,
        name,
        icon,
        productUnit,
      });
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      })
        .then(({ data }) => {
          //关闭弹窗
          this.dialogFormVisible = false;
          //添加成功后更新目录
          this.getMenu();
        })
        .catch(() => {});
    },
    submit() {
      if (this.dialogTag == "append") {
        this.saveCategory();
      }
      if (this.dialogTag == "edit") {
        this.updataCategory();
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      //计算出draggingNode最大深度
      this.getDeep(draggingNode.data);
      //计算拖拽后的总深度
      let draggingNodeDeep = this.maxLevel - draggingNode.level + 1;
      let totalDeep = draggingNodeDeep + dropNode.level;
      //console.log(totalDeep);
      if (type == "inner") {
        return totalDeep <= 3;
      } else {
        return totalDeep <= 4;
      }
    },
    //递归获取节点深度（子节点的最大level）
    getDeep(data) {
      if (data.children != null && data.children.length != 0) {
        //console.log("=========getDeep(data)的data.children==========",data.children);
        for (let i = 0; i < data.children.length; ++i) {
          //console.log(data.children[i]);
          this.maxLevel =
            data.children[i].catLevel > this.maxLevel
              ? data.children[i].catLevel
              : this.maxLevel;
          this.getDeep(data.children[i]);
        }
      }
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let parentId = 0;
      let draggingNodeLevel = 0;
      let subling = [];
      let sort = 0;
      //0.修改拖拽节点的父节点id及其level（拖拽节点的子节点的父节点id自然是不用变的）
      if (dropType == "before" || dropType == "after") {
        console.log("dropNode", dropNode);
        parentId = dropNode.level == 1 ? 0 : dropNode.parent.data.catId;
        draggingNodeLevel = dropNode.level;
        //保存dropNode的兄弟节点，包括刚拖进来的draggingNode
        subling = dropNode.parent.childNodes;
      } else {
        parentId = dropNode.data.catId;
        draggingNodeLevel = dropNode.level + 1;
        //保存dropNode的孩子节点，包括刚拖进来的draggingNode
        subling = dropNode.childNodes;
      }
      //更新draggingNode
      this.updateNodes.push({
        catId: draggingNode.data.catId,
        parentCid: parentId,
        catLevel: draggingNodeLevel,
      });
      //1.修改拖拽节点的子节点的level
      //2.修改拖拽后节点的循序：若为前后，则修改dropNode所有兄弟节点循序；若为内部则修改dropNode子节点的循序
      subling.forEach((element) => {
        //判断是否未当前被拖拽的节点，如果是，还要修改其子节点的level
        if (element.data.catId == draggingNode.data.catId) {
          console.log("==========================", element);
          this.changeLevel(element);
        }
        //修改节点的排序
        this.updateNodes.push({
          catId: element.data.catId,
          sort: sort++,
        });
      });
      //发送请求修改数据
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      })
        .then(({ data }) => {
          this.$message({
            message: "更新成功！",
            type: "success",
          });
          //更新目录
          //this.getMenu();
          //默认展开到删除节点的父节点
          this.expanded = [parentId];
          //清空this.updateNodes
          this.updateNodes = [];
          this.maxLevel = 0;
        })
        .catch(() => {
          this.$message({
            message: "更新失败！",
            type: "error",
          });
        });

      //console.log("this.updateNodes: ", this.updateNodes);
    },
    changeLevel(node) {
      if (node.childNodes.length > 0) {
        node.childNodes.forEach((element) => {
          this.updateNodes.push({
            catId: element.data.catId,
            catLevel: element.level,
          });
          this.changeLevel(element);
        });
      }
    },
  },
  created() {
    this.getMenu();
  },
};
</script>

<style>
</style>